package com.freemodbus4j.device.storage;

import java.util.Arrays;

public class Memory {

    private static volatile Memory memory;

    public static Memory getInstance() {
        if (memory == null) {
            synchronized (Memory.class) {
                if (memory == null) {
                    memory = new Memory();
                }
            }
        }
        return memory;
    }

    private Memory(){}

    // (9999+9999 + 9999*16+9999*16)/8
//    private final static int DEFAULTCAPACITY = 444498;

//    public final static byte[] STORAGE = new byte[DEFAULTCAPACITY];

    public final static byte[] COIL_00001_09999 = new byte[1250];
    public final static byte[] COIL_10001_19999 = new byte[1250];
    public final static byte[] REG_30001_39999 = new byte[19998];
    public final static byte[] REG_40001_49999 = new byte[19998];

    static {
        for (int i = 0; i < 1250; i++) {
            COIL_00001_09999[i] = 7;
        }
    }


    public byte[] readCoil(int func, int start, int end) {
        if (func == 02) {
            return Arrays.copyOfRange(COIL_10001_19999, start, end);
        }
        return Arrays.copyOfRange(COIL_00001_09999, start, end);
    }
    public byte[] readReg(int func, int start, int end) {
        if (func == 03) {
            return Arrays.copyOfRange(REG_40001_49999, start, end);
        }
        return Arrays.copyOfRange(REG_30001_39999, start, end);
    }

    public void writeCoil(int start, byte[] data) {
        System.arraycopy(data, 0, COIL_00001_09999, start, data.length);
    }

    public void writeReg(int start, byte[] data) {
        System.arraycopy(data, 0, REG_40001_49999, start, data.length);
    }
}
